// pages/mine/createPoster/index.js
var service = require('../../../service/port')

Page({
  data: {
    canvas: null,
    posterObj: {},
    posterSrc: '',
  },
  onLoad(options) {

    wx.showLoading({
      title: '生成图片中',
    })
    this.setData({
      posterObj: JSON.parse(options.param)
    })
    let that = this

    wx.getImageInfo({
      src: this.data.posterObj.url,
      success({
        path
      }) {
        that.setData({
          posterSrc: path
        })

        that.renderCanvas()
      },
      fail(err) {
        console.log(111, err)
      }
    })

  },
  renderCanvas(path) { // 绘制canvas封装

    const query = wx.createSelectorQuery()
    query.select('#qrCodeId')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        let userId = wx.getStorageSync("userInfo").id;
        let param = {
          id: userId || 1
        }
        service.getUserQRCode(param, ({
          data
        }) => {

          this.drawImage(res, data)
        })
      })

    return
    let biggerCtx = wx.createCanvasContext('bigger');
    let userId = wx.getStorageSync("userInfo").id;
    let param = {
      id: userId || 1
    }
    service.getUserQRCode(param, ({
      data
    }) => {
      this.drawPoster(data, '', 1, true);
      this.drawPoster(data, biggerCtx, 2)
    })

  },

  drawImage(res, qr) {

    const dpr = wx.getSystemInfoSync().pixelRatio
    const width = res[0].width * dpr
    const height = res[0].height * dpr

    const canvas = res[0].node
    const ctx = canvas.getContext('2d')

    this.setData({
      canvas: canvas
    })
    canvas.width = width
    canvas.height = height

    let bgImage = canvas.createImage()
    const bgImageDpr = 375 / 731
    bgImage.src = this.data.posterObj.url



    bgImage.onload = (options) => {
      console.log(options);
      if (options) {
        ctx.drawImage(bgImage, 0, 0, width, width * options.path[0].height / options.path[0].width)
        ctx.fillStyle = '#ffffff'
        ctx.fillRect(0, width * options.path[0].height / options.path[0].width, width, height - width * options.path[0].height / options.path[0].width)

        let qrImage = canvas.createImage()
        qrImage.src = qr
        qrImage.onload = () => {
          ctx.drawImage(qrImage, width - 300, width * options.path[0].height / options.path[0].width + 80, 250, 250)
          let fontText = this.data.posterObj.title
          ctx.font = '40px Arial';
          ctx.fillStyle = "#333333"

          let measure = ctx.measureText(fontText)
          let fontX = 80
          let fontY = width * options.path[0].height / options.path[0].width + 120
          ctx.fillText(fontText, fontX, fontY);
          wx.hideLoading()
        }
      }else{
        ctx.drawImage(bgImage, 0, 0, width, height - 400)
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, height- 400, width, 400)

      let qrImage = canvas.createImage()
      qrImage.src = qr 
      qrImage.onload = () => {
        ctx.drawImage(qrImage,width - 300 , height - 400 + 80 , 250 , 250 )
        let fontText = this.data.posterObj.title
        ctx.font = '40px Arial';
        ctx.fillStyle = "#333333"

        let measure = ctx.measureText(fontText)
        let fontX = 80
        let fontY = height - 400 + 120
        ctx.fillText(fontText, fontX, fontY);
        wx.hideLoading()
      }
      }


    }
  },

  savePoster() {
    let sysmInfo = wx.getSystemInfoSync()
    let dpr = sysmInfo.pixelRatio
    let width = sysmInfo.windowWidth
    let height = sysmInfo.screenHeight
    let canvas = this.data.canvas
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: width,
      height: height,
      destWidth: width,

      destHeight: height,
      canvas,
      success({
        tempFilePath
      }) {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success() {
            wx.showToast({
              title: '保存成功!',
            })
          },
        })
      },

    }, this)
  },



  drawPoster(qr, ctx, multiple, type) { // 绘制canvas
    wx.showLoading({
      title: '加载中...',
    })
    const that = this;
    multiple = multiple || 1; // 绘制倍数
    ctx = ctx || wx.createCanvasContext('poster');
    let bacImg = this.data.posterSrc; // 背景图片
    // qr = '../../../images/product.png'
    // 绘制背景色
    ctx.rect(0 * multiple, 313 * multiple, 300 * multiple, 148 * multiple);
    ctx.setFillStyle('#FFFFFF');
    ctx.fill();
    // 绘制背景图片
    ctx.drawImage(bacImg, 0 * multiple, 0 * multiple, 300 * multiple, 313 * multiple);
    // 绘制昵称
    ctx.setTextAlign('left');
    ctx.setFillStyle('#303030');
    ctx.font = `normal bold ${14 * multiple}px sans-serif`;
    let str = this.data.posterObj.title
    if (str.length > 35) {
      str = str.substring(0, 23) + '...'
    }
    let canvas = ctx
    let initX = 16 * multiple
    let initY = 361 * multiple
    let lineHeight = 40
    this.canvasTextAutoLine(str, canvas, initX, initY, lineHeight)

    // 绘制底印话术
    ctx.setFillStyle('#cccccc');
    ctx.font = `normal normal ${12 * multiple}px sans-serif`;
    // 绘制二维码图片
    ctx.drawImage(qr, 170 * multiple, 335 * multiple, 100 * multiple, 100 * multiple);
    // 绘制画布
    if (!type) {
      ctx.draw(true, function () {
        setTimeout(function () {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 600,
            height: 922,
            destWidth: 600,
            // quality: 1,
            destHeight: 922,
            canvasId: 'bigger',
            success({
              tempFilePath
            }) {
              wx.hideLoading()
              that.setData({
                posterSrc: tempFilePath
              })
            },
            fail() {

            }
          })
        }, 1000)
      })
    } else {
      ctx.draw();
    };
  },
  saveImg() { // 长按保存图片
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      fileType: 'png',
      width: 600,
      height: 922,
      destWidth: 600,
      // quality: 1,
      destHeight: 922,
      canvasId: 'bigger',
      success({
        tempFilePath
      }) {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功！'
            })
          },
          fail() {

          }
        })
      },
      fail() {

      }
    })
  },
  /*
str:要绘制的字符串
canvas:canvas对象
initX:绘制字符串起始x坐标
initY:绘制字符串起始y坐标
lineHeight:字行高，自己定义个值即可
*/
  canvasTextAutoLine(str, canvas, initX, initY, lineHeight) {
    var ctx = canvas
    var lineWidth = 0;
    var canvasWidth = 250;
    var lastSubStrIndex = 0;
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth - initX) { //减去initX,防止边界出现的问题
        ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY);

        initY += lineHeight;
        lineWidth = 0;
        lastSubStrIndex = i;
      }
      if (i == str.length - 1) {
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
      }
      ctx.setFillStyle('#707070');
      ctx.font = `normal normal 28px sans-serif`;
    }
  },


})